package com.hc.controller;

import com.alibaba.fastjson.JSON;
import com.hc.bean.*;
import com.hc.service.OrderService;
import com.hc.service.ShopCartService;
import com.hc.service.UserService;
import com.hc.utils.SendEmailUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private ShopCartService shopCartService;
    @Resource
    private OrderService orderService;

    /*获取验证码*/
    @RequestMapping("/getIdentityCode")
    @ResponseBody
    public Map<String, Object> getIdentityCode(String userEmail, HttpSession session) {
        Map<String, Object> resultMap = new HashMap<>();
        System.out.println(userEmail);
        if (userEmail != null & userEmail != "") {
            String code = UUID.randomUUID().toString().substring(0, 5);
            Thread thread = new Thread(new SendEmailUtil(userEmail, code));
            thread.start();
//            System.out.println("code*****************" + code);
            session.setAttribute("identityCoe", code);
            session.setAttribute("effectiveTime", new Date().getTime());
            resultMap.put("success", true);
            resultMap.put("message", "验证码已发送!");
        } else {
            resultMap.put("success", false);
            resultMap.put("message", "✘请输入邮箱!");
        }
        return resultMap;
    }

    /*用户注册*/
    @RequestMapping("/register")
    @ResponseBody
    public Map<String, Object> addUser(User user, HttpSession session) {
        Map<String, Object> resultMap = new HashMap<>();
        int userId = (int) new Date().getTime();
        user.setUserId(userId);
//        System.out.println("user**********" + session.getAttribute("identityCoe"));
//        System.out.println("user==========" + user.getCode());
        System.out.println(session.getAttribute("effectiveTime"));
        if (session.getAttribute("identityCoe") != null && session.getAttribute("effectiveTime") != null) {
            long effectiveTime = (long) session.getAttribute("effectiveTime");
            long nowTime = new Date().getTime();
            if ((nowTime - effectiveTime) <= 60 * 1000) {
                if (user.getCode().equals(session.getAttribute("identityCoe"))) {
                    if (userService.isExitUserName(user.getUserName())) {
                        resultMap.put("success", false);
                        resultMap.put("code", 0);
                        resultMap.put("message", "✘用户名已存在!");
                    } else {
                        /*设置注册时间*/
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String registerDate = dateFormat.format(new Date());
                        user.setUserRegisterTime(registerDate);
                        if (userService.addUser(user)) {
                            resultMap.put("success", true);
                            resultMap.put("code", 1);
                            resultMap.put("message", "用户注册成功!");
                        } else {
                            resultMap.put("success", false);
                            resultMap.put("code", 2);
                            resultMap.put("message", "用户注册失败!");
                        }
                        session.setAttribute("identityCoe", "");
                        session.setAttribute("effectiveTime", "");
                    }
                } else {
                    resultMap.put("success", false);
                    resultMap.put("code", 3);
                    resultMap.put("message", "✘验证码错误!");
                }
            } else {
                resultMap.put("success", false);
                resultMap.put("code", 3);
                resultMap.put("message", "✘验证码已过期!");
            }
        } else {
            resultMap.put("success", false);
            resultMap.put("code", 3);
            resultMap.put("message", "✘验证码已过期!");
        }
        return resultMap;
    }

    /*查询所有用户*/
    @RequestMapping("/findAll")
    @ResponseBody
    public Map<String, Object> findAll() {
        Map<String, Object> resultMap = new HashMap<>();
        List<User> userList = userService.findAll();
        if (userList.size() > 0) {
            resultMap.put("success", true);
            resultMap.put("message", "查询成功！");
            resultMap.put("userList", userList);
        } else {
            resultMap.put("success", false);
            resultMap.put("message", "查询失败！");
        }
        return resultMap;
    }

    /*用户登录*/
    @RequestMapping("/userLogin")
    @ResponseBody
    public Map<String, Object> userLogin(User user, HttpSession session, HttpServletResponse response) {
        Map<String, Object> resultMap = new HashMap<>();
        System.out.println(user);
        if (userService.isExitUserName(user.getUserName())) {
            User loginUser = userService.isPassword(user);
            if (loginUser != null) {
                session.setAttribute("user", loginUser);
                Cookie userName = new Cookie("userName", loginUser.getUserName());
                Cookie userPassword = new Cookie("userPassword", loginUser.getUserPassword());
                if (user.getAutoLogin()) {
                    userName.setMaxAge(365 * 24 * 60 * 60);
                    userPassword.setMaxAge(365 * 24 * 60 * 60);
                }else {
                    userPassword.setMaxAge(0);
                }
                response.addCookie(userName);
                response.addCookie(userPassword);

                resultMap.put("success", true);
                resultMap.put("code", 1);
                resultMap.put("message", "登录成功!");
            } else {
                resultMap.put("success", false);
                resultMap.put("code", 2);
                resultMap.put("message", "密码错误!");
            }
        } else {
            resultMap.put("success", false);
            resultMap.put("code", 0);
            resultMap.put("message", "账号不存在!");
        }
        return resultMap;
    }

    /*用户退出登录*/
    @RequestMapping("/userLogout")
    @ResponseBody
    public Map<String, Object> userLogout(HttpSession session) {
        Map<String, Object> resultMap = new HashMap<>();
        System.out.println(session.getAttribute("user"));
        session.setAttribute("user",null);
        resultMap.put("success", true);
        resultMap.put("message", "用户退出登录成功!");
        return resultMap;
    }

    /*查询购物车*/
    @RequestMapping("/getShopCartByUid")
    @ResponseBody
    public Map<String, Object> getShopCartByUid(HttpSession session) {
        Map<String, Object> resultMap = new HashMap<>();
        User user= (User) session.getAttribute("user");
        if(user!=null){
            List<ShopCart> shopCartList=shopCartService.getShopCartByUid(user.getUserId());
            if(shopCartList.size()>0){
                resultMap.put("success", true);
                resultMap.put("shopCartList", shopCartList);
                resultMap.put("message", "商品信息查询成功!");
            }else {
                resultMap.put("success", false);
                resultMap.put("message", "您的购物车中还没有商品,赶紧去寻找心意的商品吧!");
            }
        }else {
            resultMap.put("success", false);
            resultMap.put("message", "您还没有登录,请先登录!");
        }
        return resultMap;
    }

    /*把指定商品移出购物车*/
    @RequestMapping("/deleteProductFromShopCart")
    @ResponseBody
    public Map<String, Object> deleteProductFromShopCart(String shopCatIds) {
        Map<String, Object> resultMap = new HashMap<>();
        shopCatIds=shopCatIds.substring(0,shopCatIds.length()-1);
//        System.out.println(shopCatIds);
        if(shopCartService.deleteShopCart(shopCatIds)){
            resultMap.put("success", true);
            resultMap.put("message", "商品移出购物车成功!");
        }else {
            resultMap.put("success", false);
            resultMap.put("message", "商品移出购物车失败!");
        }
        return resultMap;
    }

    /*提交订单*/
    @RequestMapping("/addOrder")
    @ResponseBody
    public Map<String, Object> addOrder(@RequestBody String selectShopCartList,HttpSession session) {
        Map<String, Object> resultMap = new HashMap<>();
        User user= (User) session.getAttribute("user");
        String shopCartIds="";
        if(user!=null){
            List<ShopCart> shopCartList= JSON.parseArray(selectShopCartList,ShopCart.class);
            /*设置注册时间*/
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String orderDate = dateFormat.format(new Date());
            Order order=new Order();
            /*时间错的单位是毫秒*/
            int id=(int) (new Date().getTime()/1000);
            order.setOrderId(id);
            order.setUserId(user.getUserId());
            order.setOrderDate(orderDate);
            order.setOrderStatus(0);
            if(orderService.addOrder(order)){
                for (ShopCart shopCart : shopCartList) {
                    shopCartIds+=shopCart.getShopCartId()+",";
                    OrderDetail orderDetail=new OrderDetail();
                    orderDetail.setOrderId(order.getOrderId());
                    orderDetail.setProductId(shopCart.getProductId());
                    orderDetail.setPurchasePrice(shopCart.getProduct().getProductPrice());
                    orderDetail.setPurchaseNum(shopCart.getProductNum());
                    if(!orderService.addOrderDetail(orderDetail)){
                        resultMap.put("success", false);
                        resultMap.put("message", "订单提交失败!");
                        return resultMap;
                    }
                }
                shopCartIds=shopCartIds.substring(0,shopCartIds.length()-1);
                if(shopCartService.deleteShopCart(shopCartIds)){
                    resultMap.put("success", true);
                    resultMap.put("message", "订单提交成功!");
                }else {
                    resultMap.put("success", false);
                    resultMap.put("message", "订单提交失败!");
                }
            }else {
                resultMap.put("success", false);
                resultMap.put("message", "订单创建失败!");
            }
        }else {
            resultMap.put("success", false);
            resultMap.put("message", "您还没有登录,请先登录!");
        }
        return resultMap;
    }

    /*根据用户id查询所有订单信息*/
    @RequestMapping("/getOrderByUid")
    @ResponseBody
    public Map<String, Object> getOrderByUid(@RequestBody Pager pager, HttpSession session) {
        Map<String, Object> resultMap = new HashMap<>();
        System.out.println("hhhhh"+pager);
        User user= (User) session.getAttribute("user");
        if(user!=null){
            int total=orderService.getOrderCountByUid(user.getUserId()).size();
            if(total>0){
                List<Order> orderList=orderService.getOrderByUid(pager,user.getUserId());
                resultMap.put("success", true);
                resultMap.put("orderList", orderList);
                resultMap.put("total", total);
                resultMap.put("message", "订单信息查询成功!");
            } else {
                resultMap.put("success", false);
                resultMap.put("message", "您没有下单记录!赶紧去抢购吧!");
            }
        }else {
            resultMap.put("success", false);
            resultMap.put("message", "您还没有登录,请先登录!");
        }
        return resultMap;
    }

    /*判断用户是否已近登录*/
    @RequestMapping("/isUserLogin")
    @ResponseBody
    public Map<String, Object> isUserLogin(HttpSession session) {
        Map<String, Object> resultMap = new HashMap<>();
        User user= (User) session.getAttribute("user");
        if(user!=null){
            resultMap.put("success", true);
            resultMap.put("message", "用户已登录!");
        }else {
            resultMap.put("success", false);
            resultMap.put("message", "您还没有登录,请先登录!");
        }
        return resultMap;
    }

    /*查询所有用户*/
    @RequestMapping("/test")
    @ResponseBody
    public Map<String, Object> test() {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("success", false);
        resultMap.put("message", "您还没有登录,请先登录!");
        return resultMap;
    }
}
